import {
 getLoanTaskId, createWorkTask, getWorkTask, getLoanStatus
} from '@/api/flow/work';
import { START_ACTION, AGREE_ACTION } from '@/utils/actions';

const END_NODE_STATUS_NAME = '已结束';
const USER_CONFIRMATION_NODE_STATUS_NAME = '用户确认信息';

export default {
  data() {
    return {
      loading: false,

      // tid
      tid: '',

       // forms
      formFields: [
        {
          label: '借款金额',
          value: '1', // 1 | 0
          link: '是否可以借款（机审）',
          field: {}
        }
      ]
    };
  },

  methods: {
    // loan
    async loan() {
      this.loading = true;
      this.loanModal.visible = true;

      try {
        // this.userAuthCheck();
        // await this.getLoanStatus();
        await this.createLoadProccess();
        await this.submitLoan();

        try {
          await this.getWorkTaskStatusPromises();
        } catch (error) {
          this.$notification.error({
            message: 'Audit failed, please try again later!',
            duration: 1
          });

          throw Error(error);
        }

        this.loading = false;
        this.loanModal.visible = false;

        this.$emit('loan', this.tid);
      } catch (error) {
        console.log(error, 'dadadad');
        this.loading = false;
        this.loanModal.visible = false;
      }
    },

     // basiqConnect rule
    userAuthCheck() {
      if (!this.authentication) {
        const modalProps = {
          okButtonProps: {
            props: {
              shape: 'round'
            }
          },
          cancelButtonProps: {
            props: {
              shape: 'round'
            }
          }
        };

        this.$confirm({
          title: 'Tips',
          content: 'You need to complete your personal information and bank account information to get your loan limit!',
          cancelText: 'Cancel',
          okText: 'To perfect',
          ...modalProps,
          onOk() {
            _self.$router.push({
              name: 'ModifyBasicSettings'
            });
          }
        });

        throw new Error();
      }
    },

    // loan status
    async getLoanStatus() {
      try {
        const data = await getLoanStatus();

        return data;
      } catch (error) {
        throw Error(error);
      }
    },

    // 创建借款流程
     async createLoadProccess() {
       try {
         const data = await getLoanTaskId();

         const res = await createWorkTask(data.alias_id);
         this.tid = res.task_id;

         return res;
       } catch (error) {
         throw new Error(error);
       }
    },

    // getWorkTaskStatus
    getWorkTaskStatus() {
      return new Promise((resolve, reject) => {
        getWorkTask(this.tid)
          .then((data) => {
            const isNodeStatus = (data.status_name === END_NODE_STATUS_NAME);
            if (isNodeStatus) {
              reject(data.current_nodes[0]);
              return false;
            }
            resolve(data.current_nodes[0]);
          })
          .catch((error) => reject(error));
      });
    },

    // submitLoan
    submitLoan() {
      return new Promise((resolve, reject) => {
        this.getWorkTask()
          .then(async () => {
            this.submitAction(START_ACTION, this.actionData())
              .then(async (data) => {
                resolve(data);
              })
              .catch((error) => {
                reject(error);
              });
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    getWorkTaskStatusPromises() {
      let i = 0;
      return new Promise((resolve, reject) => {
        const timer = setInterval(async () => {
          i += 1;

          let IS_STATUS = false;
          try {
            const currentNode = await this.getWorkTaskStatus();

            IS_STATUS = (currentNode.name === USER_CONFIRMATION_NODE_STATUS_NAME);
            if (IS_STATUS) {
              window.clearInterval(timer);
              resolve();
            }
          } catch (error) {
            reject(error);
          }
          if (i >= 3) {
            window.clearInterval(timer);
            IS_STATUS ? resolve() : reject();
          }
        }, 2000);
      });
    }
  }
};
